//Copyright 2008 Kristian Gundry And Rune Juhl-Petersen
//This file is part of Plain.

//Plain is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//any later version.

//Plain is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.

//You should have received a copy of the GNU Lesser General Public License
//along with Plain.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Web;

namespace Plain.Mapping
{
	public class MappingHandler:  IMapper{
		private XmlNode section;

        
        public string Path {
            set {
                try {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(HttpContext.Current.Server.MapPath(value));
                    section = doc.SelectSingleNode("DomainUIMapping");
                } catch { }
            }
        }
	    private IDictionary<string, IDictionary<string,string>> dic = new Dictionary<string, IDictionary<string,string>>();
		private void ReadExtends(Dictionary<string,string> dict, string type, IList<string> context)
		{
			if(!context.Contains(type) && section!=null)
			{
				XmlNode node = section.SelectSingleNode("class[@name='" + type + "']");
				context.Add(type);
				if(node != null)
				{
					XmlAttribute extendAtt = node.Attributes["extends"];
					if(extendAtt != null)
					{
						string[] extends = node.Attributes["extends"].Value.Split(',');

						foreach(string extend in extends)
						{
							ReadExtends(dict, extend, context);
						}
					}

					foreach(XmlNode n in node.SelectNodes("field"))
					{
						if(n.InnerText != null && n.InnerText.Length >0)
						{
							string key = n.Attributes["name"].Value;
							if (dict.ContainsKey(key))
							{
								dict[key] = n.InnerText;
							}
							else
							{
								dict.Add(n.Attributes["name"].Value, n.InnerText);
							}
						}
					}
				}
			}
		}


		#region IMapper

		public IDictionary<string, string> GetMapping(Type t)
		{
            if (dic.ContainsKey(t.Name)) {
                return dic[t.Name];
            }else{
			Dictionary<string, string> retVal = new Dictionary<string, string>();

			ReadExtends(retVal, t.Name, new List<string>());
            dic[t.Name] = retVal;

			return retVal;}
		}
		public IDictionary<string, string> GetEnumMapping(Type t)
		{
			return null;
		}

		#endregion

			}
}
